import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Avatar } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import HandleForm from './components/HandleForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule } from './service';
import moment from 'moment';
/**
 * 操作提交
 * @param fields
 */
const handleSubmit = async (_id?: string, fields?: TableListItem) => {
  let title = _id ? '修改' : '新增';
  const hide = message.loading(`正在${title}`);
  try {
    if (_id) {
      await updateRule({
        _id,
        ...fields,
      });
    } else {
      await addRule({ ...fields });
    }
    hide();
    message.success(`${title}成功`);
    return true;
  } catch (error) {
    hide();
    message.error(`${title}失败`);
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: string[], _id: string) => {
  // console.log(selectedRows,_id,'selectedRows>>>>')
  const hide = message.loading('正在删除');
  // return
  try {
    await removeRule({
      _id: _id ? _id : selectedRows,
    });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentInfo, handleSaveCurrentInfo] = useState<TableListItem | null>(null);
  const [isDetail, setDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any>([]);
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '密码',
      dataIndex: 'password',
      hideInDescriptions: true, //详情页不显示
      hideInTable: true,
    },
    {
      title: '角色',
      dataIndex: 'access',
      search: false,
      filters: [
        { text: '普通用户', value: 'user' },
        { text: '管理员', value: 'admin' },
      ],
      valueEnum: {
        user: { text: '普通用户' },
        admin: { text: '管理员' },
      },
    },
    {
      title: '_id',
      dataIndex: '_id',
      sorter: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      search: false,
      hideInForm: true,
      render: (dom, entity) => {
        return <Avatar src={entity.avatar} alt="" />;
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      sorter: true,
      hideInForm: true,
      search: false,
      renderText: (val: string) => {
        if (!val) return '';
        return moment(val).fromNow(); // 绝对时间转化成相对时间
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      sorter: true,
      hideInForm: true,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            href="javascript:;"
            onClick={() => {
              handleModalVisible(true), handleSaveCurrentInfo(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <a
            href="javascript:;"
            onClick={() => {
              handleModalVisible(true), handleSaveCurrentInfo(record), setDetail(true);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a
            href="javascript:;"
            onClick={async () => {
              await handleRemove([], record._id as 'string');
              // 刷新
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle="用户管理"
        actionRef={actionRef}
        rowKey="_id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined />
            新增
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        columns={columns}
        form={{
          submitter: false,
        }}
        pagination={{ defaultPageSize: 5 }}
        rowSelection={{
          onChange: (selected, selectedRows) => {
            setSelectedRows(selected);
          },
        }}
      />
      <HandleForm
        onCancel={() => {
          handleModalVisible(false), handleSaveCurrentInfo({}), setDetail(false);
        }}
        modalVisible={modalVisible}
        values={currentInfo}
        isDetail={isDetail}
        onSubmit={async (values) => {
          const success = await handleSubmit(currentInfo?._id, values);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      ></HandleForm>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState, '');
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
